package cn.com.chanyue.module;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.GET;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import cn.com.chanyue.bean.Logs;
import cn.com.chanyue.bean.UrlResult;
import cn.com.chanyue.bean.Urls;
import cn.com.chanyue.tool.CodeCryption;
import cn.com.chanyue.tool.ToolUtility;

/**
 * 
 * @author Howe
 * 
 */
@IocBean(fields = { "dao" })
public class ControlModule {
	
	private static final Log log = org.nutz.log.Logs.get();

	private Dao dao;

	private final static String URL = ToolUtility.getProperty("/WEB-INF/classes/urls.properties", "url");
	private final static String KEY = ToolUtility.getProperty("/WEB-INF/classes/urls.properties", "key");

	/**
	 * 短网址访问
	 * 
	 * @param key
	 * @return
	 */
	@GET
	@At("/*")
	@Ok("redirect:${obj}")
	public String redirect(String key) {

		if (!StringUtils.isBlank(key)) {

			Urls urls = dao.fetch(Urls.class, Cnd.where("SHORTKEY", "=", key));
			if (urls != null) {

				Logs log = new Logs();
				log.setReferer(StringUtils.isBlank(Mvcs.getReq().getHeader(
						"Referer")) ? "Direct" : Mvcs.getReq().getHeader(
						"Referer"));
				log.setShortKey(key);
				log.setAccessAgent(Mvcs.getReq().getHeader("User-Agent"));
				log.setAccessTime(new Date());
				log.setAccessIp(ToolUtility.getIpAddr(Mvcs.getReq()));
				dao.insert(log);
				return urls.getLongUrl();
			} else
				return URL;
		} else
			return URL;
	}

	/**
	 * 网址缩短
	 * 
	 * @param token
	 * @param url
	 * @param key
	 * @return
	 */
	@Ok("json")
	@At("/api/short")
	public UrlResult shortlUrl(@Param("token") String token,
			@Param("url") String url, @Param("key") String key) {

		try {

			url = CodeCryption.decode("URL", url);
			if (!StringUtils.isBlank(token)
					&& token.equals(CodeCryption.encode("MD5", url + KEY))
					&& !StringUtils.isBlank(url) && ToolUtility.verifyUrl(url)) {

				if (!StringUtils.isBlank(key)) {

					Urls urls = dao.fetch(Urls.class,
							Cnd.where("SHORTKEY", "=", key));
					if (urls != null) {
						urls.setAddTime(new Date());
						urls.setTitle(ToolUtility.getUrlTitle(url));
						urls.setLongUrl(url);
						dao.update(urls);
					} else {
						urls = new Urls();
						urls.setAddTime(new Date());
						urls.setTitle(ToolUtility.getUrlTitle(url));
						urls.setLongUrl(url);
						urls.setShortKey(key);
						dao.fastInsert(urls);
					}
					return UrlResult.Short(URL + key);
				} else {

					Urls urls = dao.fetch(Urls.class, Cnd.where("LONGURL", "=", url));

					key = urls == null ? null : urls.getShortKey();

					if (!StringUtils.isBlank(key)) {
						return UrlResult.Short(URL + key);
					}
					else {
						key = ToolUtility.ShortText(url)[0];
						urls = new Urls();
						urls.setAddTime(new Date());
						urls.setTitle(ToolUtility.getUrlTitle(url));
						urls.setLongUrl(url);
						urls.setShortKey(key);
						dao.fastInsert(urls);
						return UrlResult.Short(URL + key);
					}
				}
			}
		} catch (Exception e) {
			log.debug("something wrong", e);
		}
		return UrlResult.Short(null);
	}

	/**
	 * 短网址还原
	 * 
	 * @param token
	 * @param url
	 * @return
	 */
	@Ok("json")
	@At("/api/long")
	public UrlResult longUrl(@Param("token") String token, @Param("url") String url) {

		url = CodeCryption.decode("URL", url);
		if (!StringUtils.isBlank(token)
				&& token.equals(CodeCryption.encode("MD5", url + KEY))
				&& !StringUtils.isBlank(url) && ToolUtility.verifyUrl(url)
				&& url.indexOf(URL) >= 0) {

			Urls urls = dao.fetch(Urls.class,
					Cnd.where("SHORTKEY", "=", url.replaceAll(URL, "")));
			if (urls != null)
				return UrlResult.Long(urls.getLongUrl());
		} 
		return UrlResult.Long(null);
	}

}